<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html" charset="UTF-8">
    <link rel="stylesheet" type="text/css" th:href="@{/css/chatroom.css}">
</head>
<script type="text/javascript">
    /**
     * 客户端到服务端协议 CS client-server
     * @type {{GAME_OVER: number, ADD_USER: number, MYSELF_FRAME: number, OPPONENT_FRAME: number, CANCEL_MATCH: number, MATCH_USER: number}}
     */
    const CS_PROTOCOL = {
        //用户加入大厅
        ADD_USER:0x8000,
        //匹配对手
        MATCH_USER:0x8001,
        //取消匹配
        CANCEL_MATCH:0x8002,
        //我方帧
        MYSELF_FRAME:0x8003,
        //对手帧
        OPPONENT_FRAME:0x8004,
        //游戏结束
        GAME_OVER:0x8005
    }

    /**
     * 服务端到客户端协议 SC server-client
     * @type {{OPPONENT_IS_OPERATIING: number, SERVER_PUSH_OPPONENT_FRAME: number, MATCH_USER_RESPONSE: number, ADD_USER_RESPONSE: number, SERVER_PUSH_MYSELF_FRAME: number, GAME_OVER_RESPONSE: number, CONNECTION_SUCCESS: number}}
     */
    const SC_PROTOCOL = {
        //建立 websocket 连接成功
        CONNECTION_SUCCESS:0x9000,
        //加入匹配大厅响应
        ADD_USER_RESPONSE:0x9001,
        //匹配对手响应
        MATCH_USER_RESPONSE:0x9002,
        //服务器推送本方帧
        SERVER_PUSH_MYSELF_FRAME:0x9003,
        //服务器推送对手帧
        SERVER_PUSH_OPPONENT_FRAME:0x9004,
        //结束游戏响应
        GAME_OVER_RESPONSE:0x9005,
        //对手正在操作
        OPPONENT_IS_OPERATIING:0x9006,
        //心跳
        HEART_BEAT:0x9007,
        //重连帧
        RECONNECT_FRAME:0x9008
    }

    var socket;
    var socketUrl;
    var uname;
    function connect(){
        uname = $("#uname").val();
        if(!window.WebSocket){
            window.WebSocket = window.MozWebSocket;
        }
        if(window.WebSocket){
            //测试url
            // socketUrl = "ws://127.0.0.1:12345/ws?uname="+uname;
            //正式url
            socketUrl = "ws://peakgame.com.cn:12345/ws?uname="+uname;
            socket = new WebSocket(socketUrl);

            socket.onmessage = function(msg){
                var obj = JSON.parse(msg.data);
                console.log("后端传来的数据：" + JSON.stringify(obj))
                if(obj.protocol === SC_PROTOCOL.CONNECTION_SUCCESS){
                    //服务器响应,成功建立 websocket 连接
                    textArea.value += msg.data+"\r\n";

                }else if(obj.protocol === SC_PROTOCOL.ADD_USER_RESPONSE){

                    //服务器响应,用户加入大厅
                    textArea.value += msg.data+"\r\n";

                }else if(obj.protocol === SC_PROTOCOL.MATCH_USER_RESPONSE){

                    //服务器响应,用户匹配对手
                    textArea.value += msg.data+"\r\n";
                    $("#player1").text(uname);
                    $("#player2").text(obj.data);

                }else if(obj.protocol === SC_PROTOCOL.SERVER_PUSH_MYSELF_FRAME){
                    //服务器推送本方帧
                    textArea.value += msg.data+"\r\n";

                    $("#text1").val(obj.data.text);
                    $("#player1Steps").text(obj.data.steps);

                } else if(obj.protocol === SC_PROTOCOL.SERVER_PUSH_OPPONENT_FRAME){
                    //服务器推送对手帧
                    textArea.value += msg.data+"\r\n";

                    $("#text2").val(obj.data.text);
                    $("#player2Steps").text(obj.data.steps);

                }else if(obj.protocol === SC_PROTOCOL.GAME_OVER_RESPONSE){
                    //服务哦响应，结束游戏
                    textArea.value += msg.data+"\r\n";

                }else if(obj.protocol === SC_PROTOCOL.OPPONENT_IS_OPERATIING){
                    //服务器响应，你的对手正在操作，请稍后再试
                    textArea.value += msg.data+"\r\n";

                    alert("你的对手正在操作，请稍后再试");
                }else if(obj.protocol === SC_PROTOCOL.HEART_BEAT){

                    textArea.value += msg.data+"\r\n";

                }
                else if(obj.protocol === SC_PROTOCOL.RECONNECT_FRAME){

                    //重连帧
                    textArea.value += msg.data+"\r\n";

                    let myselfFrame = obj.data['myselfFrame'];
                    let opponentFrame = obj.data['opponentFrame'];

                    $("#text1").val(myselfFrame.text);
                    $("#player1Steps").text(myselfFrame.steps);

                    $("#text2").val(opponentFrame.text);
                    $("#player2Steps").text(opponentFrame.steps);

                }
            };

            socket.onopen = function(msg){
                textArea.value += "建立 websocket 连接"+"\r\n";
            };
            socket.onclose = function(msg){
                textArea.value += "websocket 连接关闭"+"\r\n";
            };
            socket.onerror = function(msg){
                textArea.value += "websocket 发生了错误"+"\r\n";
            };
        }else{
            alert("您的浏览器不支持WebSocket协议！");
        }


    }

    function send(message){
        if(!window.WebSocket){return;}
        if(socket.readyState == WebSocket.OPEN){
            socket.send(message);
        }else{
            alert("WebSocket 连接没有建立成功！");
        }

    }

    //强制关闭浏览器  调用websocket.close（）,进行正常关闭
    window.onunload = function() {
        disConnect();
    }

    function disConnect(){
        socket.close();
    }

    // 用户进入匹配大厅
    function addUser(){
        var packet = {};
        var sender = uname;
        var protocol = CS_PROTOCOL.ADD_USER;
        packet.sender = sender;
        packet.protocol = protocol;
        send(JSON.stringify(packet))
    }

    // 随机匹配
    function matchUser(){
        var packet = {};
        var sender = uname;
        var protocol = CS_PROTOCOL.MATCH_USER;
        packet.sender = sender;
        packet.protocol = protocol;
        send(JSON.stringify(packet))
    }

    // 取消匹配
    function cancelMatch(){
        var packet = {};
        var sender = uname;
        var protocol = CS_PROTOCOL.CANCEL_MATCH;
        packet.sender = sender;
        packet.protocol = protocol;
        send(JSON.stringify(packet))
    }

    //本方帧
    function playMySelf(){

        let text1 = document.getElementById('text1').value;
        console.log("text1 =>" + text1);
        let steps = $("#player1Steps").text();
        console.log("steps =>" + steps);

        var packet = {};
        var sender = uname;
        var protocol = CS_PROTOCOL.MYSELF_FRAME;
        packet.sender = sender;
        packet.protocol = protocol;
        packet.gameFrame = {
            text:text1,
            steps:steps
        };
        send(JSON.stringify(packet))

    }

    //对手帧
    function playOpponent(){

        let text2 = document.getElementById('text2').value;
        console.log("text2 =>" + text2);
        let steps = $("#player2Steps").text();
        console.log("steps =>" + steps);

        var packet = {};
        var sender = uname;
        var protocol = CS_PROTOCOL.OPPONENT_FRAME;
        packet.sender = sender;
        packet.protocol = protocol;
        packet.gameFrame = {
            text:text2,
            steps:steps
        };
        send(JSON.stringify(packet))

    }

    // 游戏结束
    function gameOver(){
        var packet = {};
        var sender = uname;
        var protocol = CS_PROTOCOL.GAME_OVER;
        packet.sender = sender;
        packet.protocol = protocol;
        send(JSON.stringify(packet))
    }


</script>

<body>
<script type="text/javascript" th:src="@{/js/jquery.min.js}" charset="utf-8"></script>
<!--<script th:inline="javascript" th:src="@{/js/server.js}" charset="utf-8"></script>-->

<input id="uname" type="hidden" th:value="${uname}" />

用户: <span th:text="${uname}"></span>

<br>
<div class="chat-window">
    <input type="button" value="连接websocket" onclick="connect()"/>
</div>

<br>
<div class="chat-window">
    <input type="button" value="断开websocket" onclick="disConnect()"/>
</div>

<br>
<div class="chat-window">
    <input type="button" value="用户加入大厅" onclick="addUser()"/>
</div>

<br>
<div class="chat-window">
    <input type="button"  value="随机匹配" onclick="matchUser()"/>
</div>

<br>
<div class="chat-window">
    <input type="button"  value="取消匹配" onclick="cancelMatch()"/>
</div>

<br>
<div class="chat-window">
    <span>匹配对局</span>
    <div>
        本方：<span name="player1" id="player1"></span><br>
        牌数：<input type="text" name="text1" id="text1" placeholder="本方牌数"/><br>
        步骤：<span name="player1Steps" id="player1Steps"></span>
        <br>
        <button onclick="playMySelf()">确定</button>
    </div>
    <br>
    <div>
        对手：<span name="player2" id="player2"></span><br>
        牌数：<input type="text" name="text2" id="text2" placeholder="对手牌数"/><br>
        步骤：<span name="player2Steps" id="player2Steps"></span>
        <br>
        <button onclick="playOpponent()">确定</button>
    </div>
    <br>

</div>

<br>
<div class="chat-window">
    <input type="button"  value="游戏结束" onclick="gameOver()"/>
</div>

<br>
收到消息：<textarea name="textArea" id="textArea" style="width: 1000px;height: 300px;"></textarea>
</body>

</html>